package com.lagou.sqlSesssion;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import javax.jws.WebParam;
import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

/**
 * TODO
 *
 * @author harmony
 * @description
 * @date 2020/12/9 20:30
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration){
        this.configuration = configuration;
    }


    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> list = selectList(statementId, params);
        if(list.size() == 1){
            return (T) list.get(0);
        }else if(list.size() > 1){
            throw  new RuntimeException("查询结果过多");
        }else {
            throw new RuntimeException("查询无结果");
        }
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk动态代理为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            /**
             * @param proxy 当前代理对象的引用
             * @param method  当前被调用方法的引用
             * @param args  传递的参数
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层都还是执行jdbc代码，根据不同情况，来调用selectList或者selectOne
                //准备参数 1：statementId sql语句的唯一标识 namespace.id = 接口全限定名.方法名
                //方法名
                String methodName = method.getName();
                //接口全限定名
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;
                //准备参数 2：params:args

                //获取被调用方法的返回值类型
                MappedStatement mappedStatement = configuration.getMap().get(statementId);
                String sqlType = mappedStatement.getSqlType();

                switch (sqlType){
                    case "update":return update(statementId,args);
                    case "delete":return delete(statementId,args);
                    case "insert":return insert(statementId,args);
                    case "select":
                        Type genericReturnType = method.getGenericReturnType();
                        //判断返回值类型中是否包含泛型 若包含则为集合
                        if(genericReturnType instanceof ParameterizedType){
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        }
                        return selectOne(statementId,args);
                    default:break;
                }
                return null;
            }
        });

        return (T) proxyInstance;
    }

    @Override
    public Integer update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMap().get(statementId);
        Integer i = simpleExecutor.update(configuration, mappedStatement, params);
        return i;
    }

    @Override
    public Integer delete(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMap().get(statementId);
        Integer i = simpleExecutor.delete(configuration, mappedStatement, params);
        return i;
    }

    @Override
    public Integer insert(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMap().get(statementId);
        Integer i = simpleExecutor.insert(configuration, mappedStatement, params);
        return i;
    }
}
